package com.song.hander;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.song.base.exception.HeaderException;
import com.song.base.model.ResponseEntity;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    private ObjectMapper om = new ObjectMapper();

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
//        log.error("出现异常: ",ex);
        System.out.println("出现异常: "+ex);
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
            ResponseEntity<String> re = ResponseEntity.BuildError(String.class);
            if(ex instanceof HeaderException) {
                HeaderException e = (HeaderException)ex;
                re.setCode(e.getCode()).setMsg(e.getMessage()).setData(ex.getClass().getName());
            } else {
                re.setMsg(ex.getMessage() == null ? "服务器走丢了dnmd" : ex.getMessage()).setData(ex.getClass().getName());
            }
            byte[] result = null;
            try {
                result = om.writeValueAsBytes(re);
            } catch ( JsonProcessingException e) {
                e.printStackTrace();
            }
            return exchange.getResponse().bufferFactory().wrap(result);
        }));
    }
}
